<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>部门列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/static/plugin/layui/css/layui.css}" media="all">
</head>
<body>
<table class="layui-hide" id="SysDept" lay-filter="SysDept"></table>

<input type="text" id="ctx" hidden="hidden" th:value="${#request.getContextPath()}">

<!--编辑表单-->
<div class="layui-row" id="editForm" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" action="" style="margin-top:20px">
            <input type="text" id="id" name="id" hidden="hidden">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">上级部门</label>
                    <div class="layui-input-inline">
                        <input type="text" id="pname" name="pname" required lay-verify="required" autocomplete="off"
                               placeholder="" class="layui-input">
                    </div>
                    <button type="button" class="layui-btn layui-btn-sm" id="chooseDeptBtn">
                        <i class="layui-icon">&#xe615;</i>
                    </button>
                    <input type="hidden" id="pid" name="pid"/>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">部门名称</label>
                    <div class="layui-input-inline">
                        <input type="text" id="deptName" name="deptName" required lay-verify="required" autocomplete="off"
                               placeholder="" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">部门编码</label>
                    <div class="layui-input-inline">
                        <input type="text" id="deptCode" name="deptCode" required lay-verify="required" autocomplete="off"
                               placeholder="" class="layui-input">
                    </div>
                </div>
            </div>


            <div class="layui-form-item" style="margin-top:40px">
                <div class="layui-input-block">
                    <button type="button" class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="confirm">确认</button>
                    <button type="button" class="layui-btn layui-btn-primary" id="back">关闭</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script type="text/html" id="deptToolBar">
    <div class="layui-btn-container">
        <button type="button" class="layui-btn layui-btn-sm" lay-event="add" shiro:hasPermission="dept:add">新增</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-xs" lay-event="edit" shiro:hasPermission="dept:edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" shiro:hasPermission="dept:remove">删除</a>
</script>

<script th:src="@{/static/js/jquery.min.js}" charset="utf-8"></script>
<script th:src="@{/static/plugin/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{/static/js/app.js}" charset="utf-8"></script>

<script>
    layui.use(['jquery', 'table'], function () {
        var table = layui.table;
        var form = layui.form;

       var deptTable =  table.render({
            elem: '#SysDept'
            , url: ctx+'/sysDept/list'
            , method: 'post'
            , toolbar: '#deptToolBar' //开启头部工具栏，并为其绑定左侧模板
            , defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义，去除该参数即可
                title: '提示'
                , layEvent: 'LAYTABLE_TIPS'
                , icon: 'layui-icon-tips'
            }]
            , title: 'SysDept'
            , cols: [
                [
                    {field: 'id', title: 'ID', align: 'center',width: 80}
                    , {field: 'deptName', title: '部门名称', align: 'center'}
                    , {field: 'deptCode', title: '部门编码', align: 'center'}
                    , {field: 'pname', title: '上级部门', align: 'center'}
                    , {fixed: 'right', title: '操作', toolbar: '#barDemo',width: 120}
                ]
            ]
            , page: true
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": 0, //解析接口状态
                    "msg": "", //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.records //解析数据列表
                };
            }

        });
        var $ = layui.$, active = {
            reload: function () {
                var queryWhere = {};
                //执行重载
                table.reload('SysDept', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    , where: queryWhere
                    , done: function (res, curr, count) {
                        this.where = {};
                    }
                }, 'data');
            }
        };

        $('.searchTable .layui-btn').on('click', function () {
            var type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        form.on('submit(confirm)', function (massage) {
            $.ajax({
                url: ctx+'/sysDept/save',
                type: "POST",
                contentType: "application/json",
                dataType: "json",
                data: JSON.stringify(massage.field),
                success: function (data) {
                    if(data.success){
                        layer.closeAll();//关闭所有的弹出层
                        deptTable.reload();
                    }else{
                        layer.msg(data.message);
                    }
                },
                error: function (e) {
                    alert(e.message)
                }
            });

            return false;
        });

        //头工具栏事件
        table.on('toolbar(SysDept)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            switch (obj.event) {
                //自定义头工具栏右侧图标 - 提示
                case 'add':
                    //iframe层-父子操作
                {
                    var updateIndex = layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        title: "新增",
                        area: ['500px', '300px'],
                        content: $("#editForm")//引用的弹出层的页面层的方式加载修改界面表单
                    });
                    //setFormValue(obj, null);
                    $("#id").val("");
                    $("#deptName").val("");
                    $("#deptCode").val("");
                    $("#pid").val("");
                    $("#pname").val("");
                }
                    break;
            }
            ;
        });

        //监听弹出框表单提交，massage是修改界面的表单数据'submit(confirm),是修改按钮的绑定

        //监听行工具事件
        table.on('tool(SysDept)', function (obj) {
            var data = obj.data;
            // console.log(obj)
            if (obj.event === 'del') {
                layer.confirm('真的删除行么', function (index) {
                    $.ajax({
                        type: "POST",
                        url: ctx+"/sysDept/remove",
                        traditional: true,
                        data: {
                            id: data.id
                        },
                        success: function (data) {
                            layer.close(index);
                            var queryWhere = {};

                            //执行重载
                            table.reload('SysDept', {
                                page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                                , where: queryWhere
                                , done: function (res, curr, count) {
                                    this.where = {};
                                }
                            }, 'data');
                        },
                        error: function (e) {
                            console.log("ERROR: ", e);
                        }
                    });
                });
            } else if (obj.event === 'edit') {
                //iframe层-父子操作
                var updateIndex = layer.open({
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    type: 1,
                    title: "修改",
                    area: ['500px', '300px'],
                    content: $("#editForm")//引用的弹出层的页面层的方式加载修改界面表单

                });
                //alert(JSON.stringify(data))
                setFormValue(obj, data);
            }
        });

        // 填充form
        function setFormValue(obj, data){
            if(data != null){
                $("#id").val(data.id);
                $("#deptName").val(data.deptName);
                $("#deptCode").val(data.deptCode);
                $("#pid").val(data.pid);
                $("#pname").val(data.pname);
            }
        }

        $("#back").on('click', function () {
            layer.closeAll();
        });

        // 打开选择部门树页面
        $('#chooseDeptBtn').on('click', function () {
            layer.open({
                //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                type: 2,
                title: "选择部门",
                area: ['300px', '550px'],
                content: 'toSelectTree'//引用的弹出层的页面层的方式加载修改界面表单
            });
        })
    });
</script>

</body>
</html>